/*
 * @Author: xiaosihan 
 * @Date: 2023-08-10 11:24:00 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-12-07 00:25:16
 */

import { Input, Slider } from "antd";
import clsx from "clsx";
import { clamp, throttle } from "lodash";
import { autorun } from "mobx";
import { useEffect, useRef, useState } from "react";
import designTemplateEditorStore from "../../designTemplateEditorStore";
import designTemplateEditor from "../../designTemplateEditorer";
import styles from "./toolRotation.module.less";


interface Iprops {
}

// 旋转
export default function ToolRotation() {

    const dom = useRef<HTMLDivElement | null>(null);
    const [visible, setVisible] = useState(false);
    const [disable, setDisable] = useState(false);
    const [rotation, setRotation] = useState(designTemplateEditorStore.rotation);

    useEffect(() => autorun(() => {
        const { lock, activeObjectId } = designTemplateEditorStore;
        const activeObject = designTemplateEditor.fabricCanvas.getActiveObject();
        if (activeObjectId && activeObject) {
            setDisable(lock);
            setVisible(true);
        } else {
            setVisible(false);
        }
    }), []);

    useEffect(() => autorun(() => {
        setRotation(designTemplateEditorStore.rotation);
    }), []);

    const activeObjectRotation = throttle((angle: number) => {
        const activeObject = designTemplateEditor.fabricCanvas.getActiveObject();
        if (activeObject) {
            activeObject.angle = angle;
            designTemplateEditor.render();
        }
    }, 30);

    return (
        <div
            className={clsx(styles.toolRotation, visible && styles.visible, disable && styles.disable)}
        >
            <span className={styles.lable} >旋转</span>
            <Slider
                className={styles.slider}
                min={-180}
                max={180}
                value={rotation}
                onChange={v => {
                    activeObjectRotation(v);
                    designTemplateEditorStore.setRotation(v);
                }}
            />
            <Input
                key={rotation}
                className={styles.input}
                defaultValue={rotation}
                onPressEnter={e => {
                    designTemplateEditor.setRotation(Number((e.target as HTMLInputElement).value));
                }}
                onBlur={e => {
                    designTemplateEditor.setRotation(Number((e.target as HTMLInputElement).value));
                }}
                onWheel={e => {
                    const value = clamp((rotation + Math.sign(e.deltaY)), -180, 180);
                    designTemplateEditor.setRotation(value, 0);
                }}
            />
        </div>
    );

}